<template>
  <el-form :model="form" ref="formRef" :rules="formRules.rules" label-width="121px" :style="rightBoxState.hideRightBoxFlag && rightBoxState.hideRightCnFlag
    ? 'display:none'
    : !rightBoxState.hideRightBoxFlag && rightBoxState.hideRightCnFlag
      ? 'display:none'
      : ''
    ">


    <el-form-item label="甲方" prop="owner">
      <el-input class="inputStyle" v-model="form.owner" placeholder="点击选择" readonly
        @click="showOwnerDialog('leaseCustomers')" />
    </el-form-item>



    <el-form-item label="乙方" prop="customerName">
      <el-input class="inputStyle" v-model="form.customerName" placeholder="点击选择" readonly
        @click="showTenantryDialog('leaseCustomers')" />
    </el-form-item>
    <!-- 选择的租赁方客户 -->
    <!-- <div class="housesListBox" v-if="form.leaseCustomers.length">
      <el-form-item class="housesItemStyle" v-for="(n, i) in form.leaseCustomers" :key="i" :label="`乙方${i + 1}`">
        <img class="deletBtn" src="@/assets/iconImg/delet.png" alt="" @click="doDeleteLeaseCustomersList(i)" />
        <el-input v-model="n.customerName" placeholder="客户姓名" disabled />
      </el-form-item>
    </div> -->



    <el-form-item class="limitInput" label="签订日期">
      <el-date-picker v-model="form.signTime" class="dateInputBox" value-format="YYYY-MM-DD" type="date"
        placeholder="请选择签订日期" size="large" @click="selectedDom('signTime')">
      </el-date-picker>
    </el-form-item>
    <el-form-item label="经营用途" prop="businessPurpose">
      <el-input v-model="form.businessPurpose" class="inputStyle" maxlength="32" @click="selectedDom('businessPurpose')"
        placeholder="请输入经营用途" clearable />
    </el-form-item>



    <el-form-item label="租赁的资产" prop="leaseAsset">
      <el-input class="inputStyle" v-model="form.leaseAsset" placeholder="点击选择" readonly @click="() => {
        showAssetDialog();
        selectedDom('leaseHousings');
      }
        " />
    </el-form-item>
    <el-form-item label="租赁的房源" prop="haveHousingValFlag">
      <el-input class="inputStyle" v-model="form.haveHousingValFlag"
        :placeholder="form.leaseAsset === '' ? '请先选择租赁的资产' : '点击选择'" readonly :disabled="form.leaseAsset === ''" @click="() => {
          showHousingDialog();
          selectedDom('leaseHousings');
        }
          " />
    </el-form-item>

    <!-- 选择的房源列表 -->
    <div class="housesListBox" v-if="form.leaseHousings.length">
      <el-form-item class="housesItemStyle" v-for="(n, i) in form.leaseHousings" :key="i" :label="`房源${i + 1}`">
        <img class="deletBtn" src="@/assets/iconImg/delet.png" alt="" @click="doDeletHousesList(i)" />
        <el-input v-model="n.housingNumber" placeholder="门牌号" disabled />
        <el-input v-model="n.leaseArea" placeholder="租赁面积(平方米)" disabled />
      </el-form-item>
    </div>
    <el-form-item class="limitInput" label="合同期限" prop="sign_time">
      <el-date-picker v-model="form.sign_time" type="daterange" class="dateInputBox dateRangeBox"
        value-format="YYYY-MM-DD" range-separator="-" start-placeholder="开始时间" end-placeholder="结束时间"
        @change="onSignTimeChange" size="large" />
      <el-input v-model="form.monthCount" class="inputStyle" style="width: 45px" disabled placeholder="月" />
    </el-form-item>

    <el-form-item label="合同签订地址" prop="signAddress">
      <el-input v-model="form.signAddress" class="inputStyle" maxlength="32" @click="selectedDom('signAddress')"
        placeholder="合同签订地址" clearable />
    </el-form-item>

    <el-form-item label="补充协议" prop="fileVoList">
      <FileMinioUpload :restriction="true" :restrictionLimit="9" v-model:files="form.fileVoList" />
    </el-form-item>
  </el-form>

  <SelectLeaseAssetDialog ref="LeaseAssetDialogRef" @getAssetId="getAssetId" />
  <SelectLeaseHouseDialog ref="LeaseHouseDialogRef" @getHouseInfo="getHouseInfo" />
  <SelectTenantryDialog ref="TenantryDialogRef" @getTenantryInfo="getTenantryInfo" />
  <SelectTenantryDialog ref="OwnerDialogRef" @getTenantryInfo="getOwnerInfo" />
</template>

<script setup>
import {
  ElForm,
  ElFormItem,
  ElSelect,
  ElOption,
  ElDatePicker,
  ElMessage,
} from "element-plus";
import SelectLeaseAssetDialog from "@/views/assetManagement/companyContractManagement/templateManagement/components/selectLeaseAssetDialog";
import SelectLeaseHouseDialog from "@/views/assetManagement/companyContractManagement/templateManagement/components/selectLeaseHouseDialog";
import SelectTenantryDialog from "../components/SelectTenantryDialog";
import { useRouter } from "vue-router";
import { limitInputNum, localSet } from "@/common/utils/GlobalUtils";
import store from "@/store";
import {
  competeTypeOptionsArr,
  payTypeOptionsArr,
  signTypeOptionsArr,
} from "@/common/dict/dictCollect";
import { otherApi, propertyApi, customerApi } from "@/api/assets";
import { onMounted, reactive, ref, watch, defineExpose } from "vue";
import dayjs from "dayjs";
import FileMinioUpload from "@/components/FileMinioUpload.vue";
const router = useRouter();
const emits = defineEmits(["selectedDom"]);
const selectedDom = (d) => {
  emits("selectedDom", d);
};
const contractTemplateId = router.currentRoute.value.params.contractTemplateId;

// form相关
const formRef = ref(null);
const form = reactive({
  owner: "",//甲方
  ownerId: "",//甲方id
  signTime: "", //签订日期
  customerName: "", // 乙方
  fileVoList: [], // 补充协议
  signAddress: '',
  haveCustomerValFlag: "", // 仅用于'承租方(乙方)'必填的提示
  haveHousingValFlag: "", // 仅用于'租赁的房源'必填的提示
  leaseCustomers: [], // 租赁客户List
  assetsId: "", // 资产编号
  leaseHousings: [], // 房源list
  leaseTotalArea: "", //租赁总面积
  propertyDescription: "",//物业服务名称
  businessPurpose: "", // 经营用途
  payType: "1", // 支付方式（1，月，2 季，3 年）
  sign_time: "",
  assetsName: "", // 资产名字
  monthCount: '',
  propertyFeeUnitPrice: 0,
  propertyCostZN: '零元',
  // signMonthlyRent: "", // 签约实际月租
  freeRentMonth: 0, // 免租月数
  // businessPurpose: "", // 经营用途
  areaUnitPrice: "0", // 租金单价
  competitionLeaseType: 1, // 竞租方式
  increaseStartYear: "0", // 增幅开始第几年
  // increaseRate: "", // 增幅比例（%）
  signType: 1, // 签约类型(1新签2续签)
  propertyCost: 0, // 物业管理费
  // contractTemplateId: "", // 合同模板id
  address: "", // 资产地址
  deposit: "0", // 租赁保证金(押金)
  payeeId: "0", // 银行账户id
  ownerTaxIdentificationNumber: "",
  ownerBankAccountName: "",
  ownerBankAccountNumber: "",
  customerTaxIdentificationNumber: "",
  customerBankAccountName: "",
  customerBankAccountNumber: "",
  increaseRate: '0'
  // depositPayTime: "", // 租赁保证金(押金支付时间)缴纳时间
  // performanceBond: "", // 履约保证金
  // performanceTime: "", // 履约保证金缴纳时间
  // openTime: "", // 约定开始时间
  // payeeId: "", // 银行账户id
  // selectedHousesArr: [],
  // selectedLeaseCustomersArr: [],
  // term: "",
  // startDescription: "",
  // explanationOfRentFreePeriod: "",
  // programme: "",
  // integrityStatement: "",
  // businessUnit: "",
  // fileOne: "",
  // fileTwo: "",
  // fileThree: "",
  // failureToObtainDocuments: "",
  // documentsHaveBeenProcessed: "",
});


const formValidate = async () => {
  const valid = await formRef.value.validate().catch((err) => {
    //自定义catch方法，返回验证结果
    console.log(err);

    return err;
  });

  return { valid, form };
};

defineExpose({
  formValidate,
  form,
});
// 校验
const formRules = reactive({
  rules: {
    owner: [
      { required: true, trigger: "change", message: "请选择甲方" },
    ],
    customerName: [
      { required: true, trigger: "change", message: "请选择乙方" },
    ],
    haveHousingValFlag: [
      { required: true, trigger: "change", message: "请选择租赁的房源" },
    ],
    competitionLeaseType: [
      { required: true, trigger: "change", message: "请选择竟租方式" },
    ],
    leaseAsset: [{ required: true, trigger: "change", message: "请选择租赁的资产" }],
    sign_time: [{ required: true, trigger: "change", message: "请选择租赁期限" }],
    freeRentMonth: [{ required: true, trigger: "blur", message: "请输入免租月数" }],
    businessPurpose: [{ required: true, trigger: "blur", message: "请输入经营用途" }],
    // purpose: [{ required: true, trigger: "blur", message: "请输入业态" }],
    areaUnitPrice: [{ required: true, trigger: "blur", message: "请输入租金单价" }],
    increaseStartYear: [{ required: true, trigger: "blur", message: "请输入年数" }],
    increaseRate: [{ required: true, trigger: "blur", message: "请输入递增比例" }],
    payType: [{ required: true, trigger: "change", message: "请选择付款方式" }],
    propertyCost: [{ required: true, trigger: "blur", message: "请输入物业管理费" }],
    signType: [{ required: true, trigger: "change", message: "请选择签约类型" }],
    deposit: [{ required: true, trigger: "blur", message: "请输入租赁保证金额" }],
    /*depositPayTime: [
      { required: true, trigger: "change", message: "请选择缴纳时间" },
    ],*/
    openTime: [{ required: true, trigger: "change", message: "请选择约定开始时间" }],
    term: [{ required: true, trigger: "blur", message: "请输入期限" }],
    startDescription: [{ required: true, trigger: "blur", message: "请输入起始说明" }],
    propertyDescription: [{ required: true, trigger: "blur", message: "请输入物业说明" }],
    explanationOfRentFreePeriod: [
      { required: true, trigger: "blur", message: "请输入免租期说明" },
    ],
    programme: [{ required: true, trigger: "blur", message: "请输入方案" }],
    integrityStatement: [{ required: true, trigger: "blur", message: "请输入廉洁说明" }],
    businessUnit: [{ required: true, trigger: "blur", message: "请输入业务单元" }],
    fileOne: [{ required: true, trigger: "change", message: "请上传营业执照" }],
    fileTwo: [{ required: true, trigger: "change", message: "请上传身份证" }],
    fileThree: [{ required: true, trigger: "change", message: "请上传租赁区域平面图" }],
    failureToObtainDocuments: [
      { required: true, trigger: "change", message: "请输入未办理证件" },
    ],
    documentsHaveBeenProcessed: [
      { required: true, trigger: "change", message: "请输入已办理证件" },
    ],
  },
});

// 收起/展开 相关
const rightBoxState = reactive({
  hideRightBoxFlag: false, // 控制右侧整体
  hideRightCnFlag: false, // 控制右侧内容部分
});
// 收起/展开按钮点击
const doControlRight = () => {
  rightBoxState.hideRightBoxFlag = !rightBoxState.hideRightBoxFlag;
  if (rightBoxState.hideRightBoxFlag) {
    // 收起时
    setTimeout(() => {
      // 延时控制，解决收起时横向滚动条闪现问题
      rightBoxState.hideRightCnFlag = true;
    }, 200);
  } else {
    // 展开时
    setTimeout(() => {
      // 延时控制，解决展开时横向滚动条闪现问题
      rightBoxState.hideRightCnFlag = false;
    }, 200);
  }
};

const competeTypeChange = (val) => {
  selectedDom("competitionLeaseType");
};

// 房源弹窗
const LeaseHouseDialogRef = ref(null);
const showHousingDialog = () => {
  LeaseHouseDialogRef.value.open(form.assetsId, form.signType);
};

// 资产弹窗
const LeaseAssetDialogRef = ref(null);
const showAssetDialog = () => {
  LeaseAssetDialogRef.value.open();
};

const OwnerDialogRef = ref(null);
const showOwnerDialog = (className) => {
  OwnerDialogRef.value.showTenantryDialog();
  selectedDom(className);
}


// 承租方
const TenantryDialogRef = ref(null);
const showTenantryDialog = (className) => {
  TenantryDialogRef.value.showTenantryDialog();
  selectedDom(className);
};
const getOwnerInfo = (row) => {
  if (!row.customerId) {
    return ElMessage.error("脏数据!请联系管理员!");
  }
  form.owner = row.customerName
  form.ownerId = row.customerId
  form.ownerTaxIdentificationNumber = ""
  form.ownerBankAccountName = ""
  form.ownerBankAccountNumber = ""
  getBankInfo(row.customerId, "甲")
}
// 租赁方信息
const getTenantryInfo = (row) => {
  if (!row.customerId) {
    return ElMessage.error("脏数据!请联系管理员!");
  }

  form.leaseCustomers = [row];
  form.customerName = row.customerName;

  form.customerTaxIdentificationNumber = ""
  form.customerBankAccountName = ""
  form.customerBankAccountNumber = ""
  getBankInfo(row.customerId, "乙")
};

const getBankInfo = (id, type = "甲") => {
  customerApi.getBank(id).then((res) => {
    const { code, data, msg } = res;
    if (code != 200 || !data || !data.length)
      return;

    if (type == '甲') {
      form.ownerTaxIdentificationNumber = data[0].taxIdentificationNumber || ""
      form.ownerBankAccountName = data[0].bankAccountName || ""
      form.ownerBankAccountNumber = data[0].bankAccountNumber || ""
      form.ownerBankName = data[0].bankName || ""
    } else {
      form.customerTaxIdentificationNumber = data[0].taxIdentificationNumber || ""
      form.customerBankAccountName = data[0].bankAccountName || ""
      form.customerBankAccountNumber = data[0].bankAccountNumber || ""
      form.customerBankName = data[0].bankName || ""
    }
  });
}

// 房源列表删除
const doDeletHousesList = (index) => {
  form.leaseHousings.splice(index, 1);
  if (form.leaseHousings.length === 0) {
    form.haveHousingValFlag = "";
  }
  getLeaseTotalArea();
};


const getAssetId = (val) => {
  form.assetsId = val.assetsId;
  // form.assetsName = val.assetsName;
  // form.address = val.address;
  form.leaseAsset = val.assetsName;
  // form.propertyCompanyId = val.propertyCompanyId;
  // getpropertyCompanyInfo(form.propertyCompanyId)
};

const getpropertyCompanyInfo = (wuyeId) => {
  propertyApi.getPropertyInfo(wuyeId).then((res) => {
    const { code, data } = res;
    if (data) {
      form.propertyDescription = data.propertyCompanyName
      form.propertyCompanyId = data.propertyCompanyId
      form.propertyFeeUnitPrice = data.propertyFeeUnitPrice
    }

  });
}

const getHouseInfo = (val) => {
  form.leaseHousings = []
  form.leaseHousings.push({
    housingId: val.housingId,
    leaseArea: val.area,
    areaUnitPrice: 0,
    assetsName: val.assetsName,
    housingNumber: val.housingNumber || '',
    rentPricing: val.rentPricing
  });

  form.haveHousingValFlag = "已选择";
  getLeaseTotalArea();
};

//租赁开始/结束时间
const onSignTimeChange = (value) => {
  selectedDom("signStartTime");
  if (value && value !== "") {
    form.signStartTime = value[0];
    form.signEndTime = value[1];

    // 计算间隔月数
    const date1 = dayjs(value[0]);
    const date2 = dayjs(value[1]);
    form.monthCount = date2.diff(date1, "month", true).toFixed(1);
  }
};

/**
 * 租赁总面积
 */
const getLeaseTotalArea = () => {
  form.leaseTotalArea = 0;
  if (form.leaseHousings && form.leaseHousings.length !== 0) {
    form.leaseHousings.forEach((item) => {
      form.leaseTotalArea = form.leaseTotalArea + item.leaseArea;
    });
  }
};

// 租赁总面积
watch(
  () => { return form.leaseHousings },
  (value) => {
    form.leaseTotalArea = 0;
    form.propertyCost = 0;
    form.propertyCostZN = "零元"
    if (value.length !== 0) {
      form.leaseTotalArea = value[0].leaseArea;
      form.assetsName = value[0].assetsName

      form.address = value[0].housingNumber
      form.propertyFeeUnitPrice = value[0].rentPricing
      form.areaUnitPrice = value[0].rentPricing
      form.propertyCost = parseInt(value[0].rentPricing) * form.leaseTotalArea
      var nzhhk = require("nzh/hk"); //繁体中文
      form.propertyCostZN = nzhhk.encodeB(form.propertyCost);
      console.log('xx', form);
    }
  },
  { deep: true, immediate: true }
);


/**
 * 监听form,用户在输入
 */
watch(
  form,
  (value) => {
    store.commit("SET_XIN_ZU_FORM_WUYE", form);
  },
  { deep: true }
);

const initForm = () => {
  console.log(
    "store.state.collaborativeApproval.xinZuFormWuYe",
    store.state.collaborativeApproval.xinZuFormWuYe
  );
  if (
    store.state.collaborativeApproval.xinZuFormWuYe &&
    JSON.stringify(store.state.collaborativeApproval.xinZuFormWuYe) !== "{}"
  ) {
    for (let key in store.state.collaborativeApproval.xinZuFormWuYe) {
      for (let key2 in form) {
        form[key] = store.state.collaborativeApproval.xinZuFormWuYe[key];
      }
    }
  }
};

onMounted(() => {
  initForm();
});
</script>

<style lang="scss" scoped>
.rightBox {
  :deep(.el-form) {
    .el-form-item {
      margin-bottom: 21px;

      .el-form-item__content {
        .selectStyle {
          width: 100%;
          // .select-trigger {
          //   .el-input__wrapper {
          //     box-shadow: 0 0 0 1px $input-focus-bd-color inset;
          //   }
          // }
        }

        .inputStyle {
          width: 100%;

          .el-input__wrapper {
            background-color: #fff8f6;

            //box-shadow: 0 0 0 1px $input-focus-bd-color inset;
            .el-input__inner {
              text-align: center;
            }
          }
        }

        .inputCursor {
          .el-input__wrapper {
            .el-input__inner {
              cursor: pointer;
            }
          }
        }
      }
    }

    .limitInput {
      .el-form-item__content {
        display: flex;

        .dateRangeBox {
          margin-right: 6px;
          //box-shadow: 0 0 0 1px $input-focus-bd-color inset;
        }

        .dateInputBox {
          flex: 1;

          .el-input__wrapper {
            width: 100%;
            //box-shadow: 0 0 0 1px $input-focus-bd-color inset;
          }
        }

        .el-input {
          width: 100px;
        }
      }
    }
  }

  .housesListBox {
    .housesItemStyle {
      position: relative;

      .el-form-item__content {
        display: flex;

        .deletBtn {
          position: absolute;
          z-index: 1;
          left: -71px;
          cursor: pointer;
        }

        .el-input {
          flex: 1;

          &:nth-child(2) {
            margin-right: 10px;
          }
        }
      }
    }
  }
}
</style>
